package com.unittec.drainage.gateway.filter;

import javax.servlet.http.HttpServletResponse;

import com.unittec.drainage.gateway.common.GateWayConstants;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.sdk.auth.enums.BizErrorCode101;
import com.unittec.drainage.sdk.root.common.FieldConstants;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.internal.utils.SdkUtils;

@Component
public class GatewayResponseFilter extends ZuulFilter {
    @Autowired
    Log log;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletResponse response = ctx.getResponse();
        long startTime = (Long)ctx.get(GateWayConstants.REQ_START_TIME);
        GatewayRequest req = (GatewayRequest)ctx.get(GateWayConstants.SERVICECONTENT);

        if (null != req) {
            String token = ctx.getZuulRequestHeaders().get(FieldConstants.REQ_AUTHORIZATION.toLowerCase());
            req.setToken(token);
            log.debug(req, "req id 【{}】 cost time is 【{}】 ms.", req.getRequestId(),
                (System.currentTimeMillis() - startTime));
        }
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        if (response.getStatus() == HttpStatus.SC_UNAUTHORIZED) {
            ctx.getResponse().setCharacterEncoding("UTF-8");
            ctx.setResponseBody(SdkUtils
                .toJSON(Result.getewayError(req, BizErrorCode101.UNAUTHORIZED_APPLICATION, response.getStatus(), "")));
        } else if (response.getStatus() == HttpStatus.SC_NOT_FOUND) {
            ctx.getResponse().setCharacterEncoding("UTF-8");
            ctx.setResponseBody(
                SdkUtils.toJSON(Result.getewayError(req, BizErrorCode101.ERROR_APPLICATION, response.getStatus(), "")));
        } else if (response.getStatus() != HttpStatus.SC_OK) {
            ctx.getResponse().setCharacterEncoding("UTF-8");
            ctx.setResponseBody(
                SdkUtils.toJSON(Result.getewayError(req, BizErrorCode101.ERROR_APPLICATION, response.getStatus(), "")));
        } else {
            // try {
            // // 将JSON字段转换为下划线格式
            // String body = StreamUtils.copyToString(ctx.getResponseDataStream(), StandardCharsets.UTF_8);
            // ctx.setResponseBody(SdkUtils.toJSON(SdkUtils.fromJson(body, Result.class)));
            // } catch (IOException e) {
            // }
        }

        return null;
    }

}
